package com.ndood.code.template;

import java.io.CharArrayWriter;
import java.io.File;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ndood.code.entity.Column;
import com.ndood.code.entity.Table;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 模板处理类 用于替换内容
 * 
 * @author Administrator
 *
 */
public class ClientTempletUtil {

	/**
	 * 根据目录查找所有子模板 aa.txt=xxx
	 * @param columnTempletPath 
	 */
	public static Map<String, String> getTempletList(String basePath) {
		Map<String, String> map = new HashMap<String, String>();

		// 递归显示C盘下所有文件夹及其中文件
		File root = new File(basePath);
		try {
			map = showAllFiles(basePath, root);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	static Map<String, String> showAllFiles(String basePath, File dir) throws Exception {

		Map<String, String> map = new HashMap<String, String>();

		File[] fs = dir.listFiles();
		if(fs==null) {
			return map;
		}
		for (int i = 0; i < fs.length; i++) {
			File file = new File(fs[i].getAbsolutePath());
			// 将读取的子模板的内容放在map集合中

			if (fs[i].isDirectory()) {
				try {
					map.putAll(showAllFiles(basePath, fs[i]));
				} catch (Exception e) {

				}
			} else {
				map.put(file.getName(), FileUtil.getContent(fs[i].getAbsolutePath()));
			}
		}
		return map;
	}

	/**
	 * 替换内容 把子内容加上
	 * 
	 * @param oldContent 文档上下文
	 * @param map 列模板map 名称为文件名
	 * @param columns 列集合
	 */
	public static String createContent(String oldContent, Map<String, String> map, Table table) {
		// 循环所有子替换符
		for (String ks : map.keySet()) {
			String thf = "<" + ks + ">";// 替换符号
			
			// 如果是ftl模板
			if(ks.contains(".ftl") && oldContent.indexOf(thf) >= 0) {
				oldContent = replaceUpFreeMarkerContent(oldContent, table, map, ks);
				
			} else if (oldContent.indexOf(thf) >= 0) {
				String foreachContent = map.get(ks);// 列模板内容
				StringBuilder createContent = new StringBuilder();

				if(foreachContent.contains("column")||foreachContent.contains("Column")
						||foreachContent.contains("column2")||foreachContent.contains("Column2")) {
					for (Column column : table.getColumns()) {

						boolean b = true;// 控制开关
						// 只循环主键
						if (ks.indexOf(".key") >= 0) {
							if (!column.getColumnKey().equals("PRI")) {
								b = false;// 不是主键
							}
						}
						// 只循环非主键
						if (ks.indexOf(".nokey") >= 0) {
							if (column.getColumnKey().equals("PRI")) {
								b = false;// 不是主键
							}
						}

						// 只循环String 类型
						if (ks.indexOf(".String") >= 0) {
							if (!column.getColumnType().equals("String")) {
								b = false;// 不是String
							}
						}
						
						// 根据模板生成新内容
						if (b) {
							String newContent = foreachContent.replace("[column]", column.getColumnName());
							newContent = newContent.replace("[Column]", Utils.firstUpperCase(column.getColumnName()));

							newContent = newContent.replace("[column2]", column.getColumnName2());
							newContent = newContent.replace("[Column2]", Utils.firstUpperCase(column.getColumnName2()));

							newContent = newContent.replace("[type]", column.getColumnType());// java类型
							newContent = newContent.replace("[dbtype]", column.getColumnDbType());// 数据库类型
							newContent = newContent.replace("[columnComment]", column.getColumnComment());// 备注
							createContent.append(newContent);
							//System.out.println("替换后内容：" + newContent);
						}
					} 
				}
				oldContent = oldContent.replace(thf, createContent.toString());// 替换主体内容
				
			} 
			
		}

		oldContent = oldContent.replace("[table]", table.getName());
		oldContent = oldContent.replace("[Table]", Utils.firstUpperCase(table.getName()));
		oldContent = oldContent.replace("[table2]", table.getName2());
		oldContent = oldContent.replace("[Table2]", Utils.firstUpperCase(table.getName2()));

		oldContent = oldContent.replace("[comment]", table.getComment());// 备注
		if (table.getKey() != null) {
			oldContent = oldContent.replace("[key]", table.getKey());// 备注
		}
		return oldContent;
	}

	/**
	 * 列级别的freemarker模板替换，对每个表都进行替换，freemarker模板里进行循环
	 */
	private static String replaceUpFreeMarkerContent(String oldContent,Table table, Map<String,String> map, String ks) {

		String thf = "<" + ks + ">";
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
		String createContent = "";
		try {
			Template template = new Template(ks,map.get(ks),configuration);
			
			Map<String,Object> dataModel = new HashMap<String,Object>();
			dataModel.put("table", table);
			
			Writer out = new CharArrayWriter();
			template.process(dataModel, out);
			createContent = out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		oldContent = oldContent.replace(thf, createContent.toString());// 替换主体内容
		return oldContent;
	}

	/**
	 * 替换内容 把子内容加上 (替换内容)
	 */
	public static String createContentForTable(String oldContent, Map<String, String> map, List<Table> tables) {
		// 循环所有子替换符
		for (String ks : map.keySet()) {
			String thf = "<" + ks + ">";// 替换符号
			if(ks.contains(".ftl") && oldContent.indexOf(thf) >= 0) {
				oldContent = replaceUpFreeMarkerContent(oldContent, tables, map, ks);
				
			}else if (oldContent.indexOf(thf) >= 0) {
				String foreachContent = map.get(ks);// 循环体
				StringBuilder createContent = new StringBuilder();
				
				// 【关键】如果包含表格属性，则对每个表格都生成一份模板。如果不包含表格属性，只返回一个通用的模板
				if(foreachContent.contains("[table]")||foreachContent.contains("[Table]")
						||foreachContent.contains("[table2]")||foreachContent.contains("[Table2]")) {
					for (Table table : tables) {
						boolean b = true;// 控制开关
						// 根据模板生成新内容
						if (b) {
							String newContent = foreachContent.replace("[table]", table.getName());
							newContent = newContent.replace("[Table]", Utils.firstUpperCase(table.getName()));
							
							newContent = newContent.replace("[table2]", table.getName2());
							newContent = newContent.replace("[Table2]", Utils.firstUpperCase(table.getName2()));
							
							if (table.getKey() != null) {
								newContent = newContent.replace("[key]", table.getKey());
							}
							newContent = newContent.replace("[comment]", table.getComment());// 备注
							createContent.append(newContent);
						}
					}
				}
				oldContent = oldContent.replace(thf, createContent.toString());// 替换主体内容
			}
		}

		return oldContent;
	}

	/**
	 * 表级别的freemarker模板替换，对每个表都进行替换，freemarker模板里进行循环
	 */
	private static String replaceUpFreeMarkerContent(String oldContent, List<Table> tables, Map<String, String> map,
			String ks) {
		String thf = "<" + ks + ">";
		Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
		String createContent = "";
		try {
			Template template = new Template(ks,map.get(ks),configuration);
			
			Map<String,Object> dataModel = new HashMap<String,Object>();
			dataModel.put("tables", tables);
			
			Writer out = new CharArrayWriter();
			template.process(dataModel, out);
			createContent = out.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		oldContent = oldContent.replace(thf, createContent.toString());// 替换主体内容
		return oldContent;
	}

	/**
	 * 替换全局属性
	 */
	public static String createContent(String oldContent, Map<String, String> map) {
		// 循环所有子替换符
		for (String ks : map.keySet()) {
			oldContent = oldContent.replace("[" + ks + "]", map.get(ks));
		}
		return oldContent;
	}

}
